package com.laoyang.dtp;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author:Kevin
 * @create: 2023-10-24 21:57
 * @Description: 注册配置文件bean
 */

public class DtpImportBeanDefinationRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    //传入配置文件对象
    private Environment environment;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        //注册bean,读取用户配置的dtp后面定义的线程池列表，然后转换为DtpProperties对象
        DtpProperties dtpProperties = new DtpProperties();

        Binder binder = Binder.get(environment);
        ResolvableType type = ResolvableType.forClass(DtpProperties.class);
        Bindable<?> target = Bindable.of(type).withExistingValue(dtpProperties);
        binder.bind("dtp",target);

        //遍历配置，拿到所有的线程池列表
        for (DtpProperties.DtpExecutorProperties executorProperties : dtpProperties.getDtpExecutors()) {
            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
            beanDefinition.setBeanClass(DtpExecutor.class);
            //往这个DtpExecutor的有参函数中传入两个值
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(executorProperties.getCorePoolSize());
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(executorProperties.getMaximumPoolSize());

            registry.registerBeanDefinition(executorProperties.getName(),beanDefinition);

        }


    }

    //
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
